/*
 * @author Chris
 * @since 2023/1/27 16:04
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023/1/27     Chris        the first version
 */

#include "reg51.h"
#include "string.h"

extern void InitLcd1602();

extern void LcdShowStr(unsigned char x, unsigned char y, unsigned char *str, unsigned int len);

__bit flag500ms = 0;
unsigned char T0RH = 0;
unsigned char T0RL = 0;

unsigned char __code str1[] = "Kingst Studio";
unsigned char __code str2[] = "Let's move...";

void ConfigTimer0(unsigned int ms);

int main() {
    ConfigTimer0(10);
    InitLcd1602();

    unsigned char __pdata bufMove1[16 + sizeof(str1) + 16];
    memset(bufMove1, ' ', 16);
    strcpy(bufMove1 + 16, str1);
    memset(bufMove1 + 16 + sizeof(str1) - 1, ' ', 16);

    unsigned char __pdata bufMove2[16 + sizeof(str2) + 16];
    memset(bufMove2, ' ', 16);
    strcpy(bufMove2 + 16, str2);
    memset(bufMove2 + 16 + sizeof(str2) - 1, ' ', 16);

    unsigned char index = 0;
    while (1) {
        if (flag500ms) {
            flag500ms = 0;

            LcdShowStr(0, 0, bufMove1 + index, 16);
            LcdShowStr(0, 1, bufMove2 + index, 16);
            index++;
            if (index >= (16 + sizeof(str1) - 1)) {
                index = 0;
            }
        }
    }
}

void ConfigTimer0(unsigned int ms) {
    EA = 1;      // 使能总中断
    TMOD = TMOD & 0xF0 | 0x01; // 设置 T0 为模式 1
    unsigned long tmp = (65536 - ms * (11059200 / 12) / 1000 + 12); // 后面的 12 表示弥补中断误差
    T0RH = tmp >> 8;  // 为 T0 赋初值
    T0RL = tmp & 0x00FF;
    TH0 = T0RH;
    TL0 = T0RL;

    ET0 = 1;     // 使能 T0 中断
    TR0 = 1;     // 启动 T0
}

/**
 * 定时器 T0 中断服务函数
 */
void InterruptTimer0() __interrupt(1) {
    static unsigned char cnt500ms = 0;

    TH0 = T0RH;
    TL0 = T0RL;

    cnt500ms++;
    if (cnt500ms >= 50) {
        flag500ms = 1;
        cnt500ms = 0;
    }
}